package com.daxue.localclient.grpc;

import com.daxue.grpc.lib.HelloReply;
import com.daxue.grpc.lib.HelloRequest;
import com.daxue.grpc.lib.SimpleGrpc;
import com.daxue.grpc.lib.UserGrpc;
import com.daxue.grpc.lib.UserRequest;
import com.daxue.grpc.lib.UserResponse;
import io.grpc.StatusRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author daxue0929
 * @date 2022/08/31
 * GrpcClientService类有几处要注意的地方：
 * 用@Service将GrpcClientService注册为spring的普通bean实例；
 * <p>
 * 用@GrpcClient修饰SimpleBlockingStub，这样就可以通过grpc-client-spring-boot-starter库发起gRPC调用，被调用的服务端信息来自名为local-grpc-server的配置；
 * <p>
 * SimpleBlockingStub来自前文中根据helloworld.proto生成的java代码；
 * <p>
 * SimpleBlockingStub.sayHello方法会远程调用local-server应用的gRPC服务；
 * <p>
 * 为了验证gRPC服务调用能否成功，再新增个web接口，接口内部会调用GrpcClientService.sendMessage，这样咱们通过浏览器就能验证gRPC服务是否调用成功了：
 **/
@Service
@Slf4j
public class GrpcClientService {

    private final SimpleGrpc.SimpleBlockingStub simpleStub;

    private final UserGrpc.UserBlockingStub userBlockingStub;

    @Autowired
    public GrpcClientService(SimpleGrpc.SimpleBlockingStub simpleStub, UserGrpc.UserBlockingStub userBlockingStub) {
        this.simpleStub = simpleStub;
        this.userBlockingStub = userBlockingStub;
    }

    public String sendMessage(final String name) {
        try {
            final HelloReply response = this.simpleStub.sayHello(HelloRequest.newBuilder().setName(name).build());
            return response.getMessage();
        } catch (final StatusRuntimeException e) {
            return "FAILED with " + e.getStatus().getCode().name();
        }
    }

    public UserResponse sendUser() {
        UserRequest build = UserRequest.newBuilder()
            .setId(1)
            .setName("大雪")
            .setPassword("wangxuedi")
            .setAge(27).build();
        UserResponse userResponse = this.userBlockingStub.sendUser(build);
        return userResponse;
    }
}
